package permission

import (
	"context"
	"fmt"
	"github.com/mojocn/base64Captcha"
	"private-domain-overseas-service/pkg/xerr"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

// 验证码存储
var store = base64Captcha.DefaultMemStore

type AdminStaticCaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取密码登录验证码
func NewAdminStaticCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminStaticCaptchaLogic {
	return &AdminStaticCaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminStaticCaptchaLogic) AdminStaticCaptcha() (resp *types.AdminStaticCaptchaResponse, err error) {
	id, imgBuf, err := GenerateCaptcha()
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("生成验证码图片失败: %v", err.Error()))
	}

	return &types.AdminStaticCaptchaResponse{
		StaticCaptchaImage: imgBuf,
		StaticCaptchaId:    id,
	}, nil
}

func GenerateCaptcha() (string, string, error) {
	driver := &base64Captcha.DriverString{
		Height:          82,
		Width:           400,
		ShowLineOptions: base64Captcha.OptionShowHollowLine,
		Length:          4,
		Source:          "23456789abcdefghjkmnpqrstuvwxyz",
	}

	// 创建验证码实例
	captcha := base64Captcha.NewCaptcha(driver, store)

	// 生成验证码（id为随机生成，但答案固定为输入字符串）
	id, b64s, answer, err := captcha.Generate()
	if err != nil {
		return "", "", err
	}

	err = store.Set(id, answer)
	if err != nil {
		return "", "", err
	}
	return id, b64s, nil
}
